package com.spsy.order.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author 沈昕希  &&  (=￣ω￣=)m
 * @Shen "再说错了又能怎么样呢？人生不就是由无数的错误组成的吗"
 * @xin "我是个无聊的人，我有无数的缺点，我也并不喜欢我自己，甚至厌恶我自己"
 * @date 2025/9/24-20:30
 */

public class MiniThreadPool {

    private final BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();

    private final List<Thread> workers = new ArrayList<>();

    private volatile boolean isRunning = true;

    public MiniThreadPool(int threadCount) {

        for (int i = 0; i < threadCount; i++) {
            Thread worker = new Thread(() -> {

                while (isRunning || !tasks.isEmpty()) {
                    try {

                        Runnable task = tasks.take();

                        task.run();
                    } catch (InterruptedException e) {
                        // 捕获中断异常，退出循环
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
            }, "Worker-" + i);
            workers.add(worker);
            worker.start();
        }
    }

    // 提交任务
    public void submit(Runnable task) {
        if (!isRunning) {
            throw new IllegalStateException("线程池已关闭");
        }
        try {
            tasks.put(task); // 任务放入队列
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // 关闭线程池
    public void shutdown() {
        isRunning = false;

        for (Thread worker : workers) {

        }
    }

    // 测试
    public static void main(String[] args) {

        MiniThreadPool pool =  new MiniThreadPool(10); ;


        for (int i = 0; i < 10; i++) {
            int taskId = i;
            pool.submit(() -> {
                System.out.println("任务" + taskId + "由" + Thread.currentThread().getName() + "执行");
                try {
                    Thread.sleep(500);

                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }

        pool.shutdown();
    }

}
